package com.xexun.gpstracker.my.activity;

import java.util.ArrayList;
import java.util.List;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.*;

import org.json.JSONArray;
import org.json.JSONObject;
import org.xutils.view.annotation.Event;
import org.xutils.view.annotation.ViewInject;
import org.xutils.x;

import com.xexun.gpstracker.AppContext;
import com.xexun.gpstracker.channel.R;
import com.xexun.gpstracker.base.BaseActivity;
import com.xexun.gpstracker.common.CommonRestPath;
import com.xexun.gpstracker.common.Constants;
import com.xexun.gpstracker.common.MyConstants;
import com.xexun.gpstracker.fix.swipemenu.*;
import com.xexun.gpstracker.inter.HttpCallback;
import com.xexun.gpstracker.my.adapter.DSPSelectorAdapter;
import com.xexun.gpstracker.pojo.Device;
import com.xexun.gpstracker.pojo.Music;
import com.xexun.gpstracker.pojo.ResponseData;
import com.xexun.gpstracker.service.PlayerService;
import com.xexun.gpstracker.util.*;

/**
 *
 */
public class DSPSelectorActivity extends BaseActivity {
    private SwipeMenuListView musicListView;

    DSPSelectorAdapter dspSelectorAdapter;
    private String termImei;
    private List<Music> musicList = new ArrayList<>();
    private int currPage = 1;
    private int lastPage = 1;
    private Context mContext;
    private final static String TAG_AUDITION = "TAG_AUDITION";
    private int position = 0;

    @ViewInject(R.id.prev_page)
    Button prevPageButton;

    @ViewInject(R.id.next_page)
    Button nextPageButton;

    @Override
    protected void onDestroy() {
        PlayerService player = PlayerService.getPlayer();
        if (player != null) {
            player.stop();
        }
        super.onDestroy();
    }

    @Override
    protected void onResume() {
        PlayerService player = PlayerService.getPlayer();
        if (player != null) {
            player.stop();
        } else {
            Intent intent = new Intent(DSPSelectorActivity.this, PlayerService.class);
            startService(intent);
        }
        getWifi();
        super.onResume();
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_dsp_selector);
        x.view().inject(this);
        mContext = DSPSelectorActivity.this;

        termImei = getIntent().getStringExtra("IMEI");
        position = getIntent().getIntExtra("POSITION", 0);

        dspSelectorAdapter = new DSPSelectorAdapter(this, musicList, termImei, position);
        musicListView = (SwipeMenuListView) findViewById(R.id.music_selector_listview);
        musicListView.setAdapter(dspSelectorAdapter);
        musicListView.setMenuCreator(creator);
        musicListView.setOnMenuItemClickListener(onMenuItemClickListener);
        musicListView.setViewProcessor(new SwipeMenuListView.ViewProcessor() {
            @Override
            public void execute(SwipeMenuLayout layout, int position) {
                Music music = musicList.get(position);
                TextView currTxtView = (TextView) layout.findViewWithTag(SwipeMenuView.TAG_SWIPE_MEUN_VIEW_TEXT);
                if (currTxtView != null) {
                    currTxtView.setText(music.isPlaying() ? R.string.stop : R.string.audition);
                }
            }
        });

        //加载第一页
        loadPage(1);
    }

    public ListView getMusicListView() {
        return musicListView;
    }

    private SwipeMenuCreator creator = new SwipeMenuCreator() {
        @Override
        public void create(SwipeMenu menu) {
            int titleSize = 18;
            SwipeMenuItem auditionItem = new SwipeMenuItem(AppContext.getContext());
            auditionItem.setBackground(new ColorDrawable(Color.rgb(0xC9, 0xC9, 0xCE)));
            auditionItem.setWidth(Utils.dp2px(AppContext.getContext(), 80f));
            auditionItem.setTitle(R.string.audition);
            auditionItem.setTitleSize(titleSize);
            auditionItem.setTitleColor(Color.WHITE);
            auditionItem.setTag(TAG_AUDITION);
            menu.addMenuItem(auditionItem);

            SwipeMenuItem updateItem = new SwipeMenuItem(AppContext.getContext());
            updateItem.setBackground(new ColorDrawable(Color.parseColor("#9F3131")));
            updateItem.setWidth(Utils.dp2px(AppContext.getContext(), 170f));
            updateItem.setTitle(R.string.download2watch);
            updateItem.setTitleSize(titleSize);
            updateItem.setTitleColor(Color.WHITE);
            menu.addMenuItem(updateItem);
        }
    };

    private SwipeMenuListView.OnMenuItemClickListener onMenuItemClickListener = new SwipeMenuListView.OnMenuItemClickListener() {
        @Override
        public boolean onMenuItemClick(final int position, SwipeMenu menu, int index) {
            switch (index) {
                case 0:
                    dspSelectorAdapter.audition(position);
                    break;
                case 1:
                    dspSelectorAdapter.download2WatchWrap(position);
                    break;
                default:
                    break;
            }
            return false;
        }
    };

    @Event(value = R.id.music_selector_listview, type = AdapterView.OnItemClickListener.class)
    private void listItemOnClick(AdapterView<?> parent, View view, int position, long id) {
        musicListView.smoothOpenMenu(position);
    }


    @Event(R.id.prev_page)
    private void prevOnClick(View v) {
        int to = --currPage;
        if (to < 1) {
            currPage = 1;
            Toast.makeText(DSPSelectorActivity.this, R.string.page_start_note, Toast.LENGTH_SHORT).show();
        } else {
            loadPage(to);
        }
    }

    @Event(R.id.next_page)
    private void nextOnClick(View v) {
        if (lastPage < 1) {
            lastPage = 1;
        }
        int to = ++currPage;
        if (to > lastPage) {
            currPage = lastPage;
            Toast.makeText(DSPSelectorActivity.this, R.string.page_end_note, Toast.LENGTH_SHORT).show();
        } else {
            loadPage(to);
        }
    }

    public void resetSwipMenu() {
        dspSelectorAdapter.setCurrPosition(-1);
        for (int i = 0; i < musicListView.getChildCount(); i++) {
            View view = musicListView.getChildAt(i);
            if (view != null) {
                TextView currTxtView = (TextView) view.findViewWithTag(SwipeMenuView.TAG_SWIPE_MEUN_VIEW_TEXT);
                if (currTxtView != null) {
                    currTxtView.setText(R.string.audition);
                }
                View playingLayout = view.findViewById(R.id.playing);
                if (playingLayout != null) {
                    playingLayout.setVisibility(View.GONE);
                }
            }
        }
    }

    private void loadPage(final int to) {
        resetSwipMenu();
        try {
            JSONObject json = new JSONObject();
            json.putOpt("page", to);
            json.putOpt("imei", termImei);
            json.putOpt("position", position + 1);//从1开始
            HttpCallback callback = new HttpCallback() {
                @Override
                public void onStart() {
                    CommUtil.showProcessing(musicListView, true, false);
                }

                @Override
                public void onFinish() {
                }

                @Override
                public void onSuccess(ResponseData obj) {
                    CommUtil.hideProcessing();
                    if (obj.getRetcode() != 1) {
                        Toast.makeText(DSPSelectorActivity.this, R.string.load_audio_list_failed, Toast.LENGTH_SHORT).show();
                        return;
                    }
                    try {
                        JSONObject body = obj.getBody();
                        lastPage = body.optInt("pageCount");
                        int pageSize = body.optInt("pageSize", 10);
                        JSONArray array = body.getJSONArray("data");
                        if (array != null && array.length() > 0) {
                            musicList.clear();
                            for (int i = 0; i < array.length(); i++) {
                                JSONObject jsonObject = array.getJSONObject(i);
                                Music music = new Music();
                                music.setId(jsonObject.getInt("audioId"));
                                music.setUrl(jsonObject.optString("audioUrl"));
                                String name = jsonObject.optString("audioName");
                                int idx;
                                if (CommUtil.isNotBlank(name) && (idx = name.indexOf('_')) != -1) {
                                    name = name.substring(idx + 1, name.length());
                                }
                                music.setName(name);
//                                music.setFileSize(jsonObject.optInt("audioSize"));
                                music.setSerial((to - 1) * pageSize + i + 1);
                                music.setStatus(jsonObject.optInt("recordState"));
                                musicList.add(music);

                            }
                            dspSelectorAdapter.notifyDataSetChanged();
                        }
                    } catch (Exception e) {
                        Log.e(Constants.TAG, "获取列表失败！", e);
                    }
                }

                @Override
                public void onFailure(String message) {
                    CommUtil.hideProcessing();
                    Toast.makeText(DSPSelectorActivity.this, R.string.load_audio_list_failed, Toast.LENGTH_SHORT).show();
                }
            };
            HttpUtil.post(CommonRestPath.audioList(), json, new JsonHttpResponseHelper(callback).getHandler());
        } catch (Exception e) {
            Log.e(Constants.TAG, "获取分页失败！", e);
        }
    }


    private void getWifi() {
        Device.getWifi(mContext,termImei, new HttpCallback() {
            @Override
            public void onStart() {
            }

            @Override
            public void onFinish() {

            }

            @Override
            public void onSuccess(ResponseData obj) {
                //接收的wifi信息会自动排序，所以只需判断第一个wifi是否存在即可
                if (obj.getRetcode() == 1) {
                    JSONObject json = JSONHelper.getJSONObject(obj.getBodyArray(), 0);
                    SharedPreferences mSharedPreferences = Utils.getPreferences(mContext);
                    if (CommUtil.isBlank(JSONHelper.getString(json, "wifi"))) {
                        //如果为空，则说明没有wifi账号信息
                        mSharedPreferences.edit().putBoolean(MyConstants.TERMINAL_NETWORK, false).apply();
                    } else {
                        //存在账号信息
                        mSharedPreferences.edit().putBoolean(MyConstants.TERMINAL_NETWORK, true).apply();
                    }
                } else {
                    Toast.makeText(mContext, obj.getMsg(), Toast.LENGTH_SHORT).show();
                }
            }

            @Override
            public void onFailure(String message) {
            }
        });
    }

}
